<template>
  <div id="3d">
    <h1 style="position: fixed;">3D场景:</h1>
    <el-button style="position: fixed;top: 10%;" @click="test()">测试</el-button>
  </div>
</template>

<script>
  import userApi from '../../../api/cby/user.js'
  export default {
    data() {
      return {
        cubeList: [],
      }
    },
    mounted() {
      this.init3D()
    },
    methods: {
      init3D() {
        // 创建场景
        var scene = new THREE.Scene();
        // 添加摄像机
        var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
        // 创建渲染器
        var renderer = new THREE.WebGLRenderer();
        // 设置渲染器的初始颜色（背景颜色）
        renderer.setClearColor(new THREE.Color(0xEEEEEE))
        // 设置输出canvas画面的大小
        renderer.setSize(window.innerWidth, window.innerHeight * 0.961);
        // 设置渲染物体阴影
        renderer.shadowMap.enabled = true
        // 显示三维坐标系 20: 坐标轴显示的长度  旧版本是AxisHelper，新版本是AxesHelper
        var axes = new THREE.AxesHelper(20)
        scene.add(axes);
        // 创建地面  (60,20): 地面尺寸
        var planeGeometry = new THREE.PlaneGeometry(60, 20)
        var planeMaterial = new THREE.MeshLambertMaterial({
          color: 0xcccccc
        })
        var plane = new THREE.Mesh(planeGeometry, planeMaterial)
        plane.rotation.x = -0.5 * Math.PI
        plane.position.x = 15
        plane.position.y = 0
        plane.position.z = 0
        plane.receiveShadow = true // 对象是否可以接收阴影
        plane.castShadow = true // 对象是否渲染到阴影贴图中
        scene.add(plane);
        // 创建正方体
        var geometry = new THREE.BoxGeometry(4, 4, 4);
        var material = new THREE.MeshLambertMaterial({
          color: 0x00ff00
        });
        var cube = new THREE.Mesh(geometry, material);
        cube.position.y = 2
        cube.castShadow = true
        cube.receiveShadow = true
        scene.add(cube);
        // 创建球体
        var sphereGeometry = new THREE.SphereGeometry(2, 20, 20);
        var sphereMaterial = new THREE.MeshLambertMaterial({
          color: 0x00ff00
        });
        var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial);
        sphere.position.set(0, 2, 8)
        sphere.castShadow = true
        scene.add(sphere);
        // 创建聚光灯
        var spotLight = new THREE.SpotLight(0xFFFFFF)
        spotLight.position.set(-10, 15, 30)
        spotLight.castShadow = true
        // 阴影精度调整
        spotLight.angle = Math.PI / 6
        spotLight.shadow.penumbra = 0.05
        spotLight.shadow.mapSize.width = 1024
        spotLight.shadow.mapSize.innerHeight = 1024
        scene.add(spotLight);
        // 创建轨道控制器
        var orbitController = new THREE.OrbitControls(camera, renderer.domElement)
        orbitController.addEventListener('change', () => {
          renderer.render(scene, camera)
        })
        // 摄像机坐标设置
        camera.position.x = -60;
        camera.position.y = 80;
        camera.position.z = 60;
        camera.lookAt(scene.position)
        // 将渲染器输出添加到html元素中
        document.getElementById("3d").appendChild(renderer.domElement);
        // 动画
        var b = true

        function animate() {
          requestAnimationFrame(animate);
          cube.rotation.y += 0.01;
          if (b == true) {
            sphere.position.y += 0.02
          } else {
            sphere.position.y -= 0.02
          }
          if (sphere.position.y > 8) {
            b = false
          }
          if (sphere.position.y < 2) {
            b = true
          }
          renderer.render(scene, camera);
        }
        animate();
      },
      test() {
        userApi.test3D()
          .then((response) => {
            // 请求成功
            console.log(response.data.cubeList)
            this.cubeList = response.data.cubeList
            // 创建场景
            var scene = new THREE.Scene();
            // 添加摄像机
            var camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 0.1, 2000);
            // 创建渲染器
            var renderer = new THREE.WebGLRenderer();
            // 设置渲染器的初始颜色（背景颜色）
            renderer.setClearColor(new THREE.Color(0xEEEEEE))
            // 设置输出canvas画面的大小
            renderer.setSize(window.innerWidth, window.innerHeight * 0.961);
            // 设置渲染物体阴影
            renderer.shadowMap.enabled = true
            // 显示三维坐标系 20: 坐标轴显示的长度  旧版本是AxisHelper，新版本是AxesHelper
            var axes = new THREE.AxesHelper(500)
            scene.add(axes);
            // 创建地面  (60,20): 地面尺寸
            var planeGeometry = new THREE.PlaneGeometry(60, 20)
            var planeMaterial = new THREE.MeshLambertMaterial({
              color: 0xcccccc
            })
            var plane = new THREE.Mesh(planeGeometry, planeMaterial)
            plane.rotation.x = -0.5 * Math.PI
            plane.position.x = 15
            plane.position.y = 0
            plane.position.z = 0
            plane.receiveShadow = true // 对象是否可以接收阴影
            plane.castShadow = true // 对象是否渲染到阴影贴图中
            scene.add(plane);
            // 创建正方体
            for (let i = 0; i < this.cubeList.length; i++) {
              let cubeObj = this.cubeList[i]
              let geometry = new THREE.BoxGeometry(cubeObj.l,cubeObj.w,cubeObj.h);
              // let material = new THREE.MeshLambertMaterial({
              //   color: 0x00ff00
              // });
              // 贴图
              let map = new THREE.TextureLoader().load('https://cdn.jsdelivr.net/gh/WSKH0929/images/TexturesCom_WoodStudded0042_1_seamless_S.jpg')
              let material = new THREE.MeshLambertMaterial();
              material.map = map
              let cube = new THREE.Mesh(geometry, material);
              cube.position.set(cubeObj.x,cubeObj.y,cubeObj.z)
              cube.castShadow = true
              cube.receiveShadow = true
              scene.add(cube);
            }
            // 创建聚光灯
            var spotLight = new THREE.SpotLight(0xFFFFFF)
            spotLight.position.set(-1000, 1500, 3000)
            spotLight.castShadow = true
            // 阴影精度调整
            spotLight.angle = Math.PI / 6
            spotLight.shadow.penumbra = 0.05
            spotLight.shadow.mapSize.width = 1024
            spotLight.shadow.mapSize.innerHeight = 1024
            scene.add(spotLight);
            // 创建轨道控制器
            var orbitController = new THREE.OrbitControls(camera, renderer.domElement)
            orbitController.addEventListener('change', () => {
              renderer.render(scene, camera)
            })
            // 摄像机坐标设置
            camera.position.x = -600;
            camera.position.y = 800;
            camera.position.z = 600;
            camera.lookAt(scene.position)
            // 将渲染器输出添加到html元素中 .replaceChild(0)
            let father = document.getElementById("3d")
            father.removeChild(father.children[2])
            document.getElementById("3d").appendChild(renderer.domElement);
            renderer.render(scene, camera);
          })
          .catch((error) => {
            console.log(error);
          });
      },
    }
  }
</script>

<style>
</style>
